﻿using Sidvall.Serialization;

namespace Sidvall.AuthorizationManager.Data.Keys
{
    public class ResourceItemIndex
    {
        public long AuthorizationScopeId { get; set; }
        public string Resource { get; set; }
        public string ResourceItemId { get; set; }
        
        public static ResourceItemIndex GetKey(IAuthorizationScopeResourceItem item)
        {
            if (item == null)
                return null;
            if (item.Resource == null)
                return null;
            if (item.ResourceItemId == null)
                return null;
            return new ResourceItemIndex()
            {
                AuthorizationScopeId = item.AuthorizationScopeId,
                Resource = item.Resource,
                ResourceItemId = item.ResourceItemId,
            };
        }
        public static ResourceItemIndex GetKey(long authorizationScopeId, string resource, string resourceItemId)
        {
            if (resource == null)
                return null;
            if (resourceItemId == null)
                return null;
            return new ResourceItemIndex()
            {
                AuthorizationScopeId = authorizationScopeId,
                Resource = resource,
                ResourceItemId = resourceItemId,
            };
        }
        public static ResourceItemIndex ParseKey(string key)
        {
            var values = key.Split("|*.");
            return new ResourceItemIndex()
            {
                AuthorizationScopeId = values[0].ToNullableInt64().Value,
                Resource = values[1],
                ResourceItemId = values[2],
            };
        }
        public override string ToString()
        {
            return this.AuthorizationScopeId.ToString(System.Globalization.CultureInfo.InvariantCulture) + "|*." + this.Resource + "|*." + this.ResourceItemId;
        }
    }
}